package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class CommentApiImpl implements CommentApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //查询互动数据
    public List<Comment> findComments(Integer page, Integer pagesize,
                                      String movementId, int commentType) {

        Criteria criteria = Criteria.where("publishId").is(new ObjectId(movementId))
                                    .and("commentType").is(commentType);
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        return mongoTemplate.find(query,Comment.class);
    }


    /**
     * 保存评论，点赞，喜欢
     *  返回值：
     *     评论：返回总评论数
     *     点赞：返回总点赞数
     *     喜欢：。。。。。。
     */
    //保存互动数据
    public Integer save(Comment comment) {
        //1、查询动态，获取动态发布人的id，设置到comment对象
        ObjectId movementId = comment.getPublishId();
        Movement movement = mongoTemplate.findById(movementId, Movement.class);
        comment.setPublishUserId(movement.getUserId()); //设置动态发布人id
        //2、保存到MongoDB中
        mongoTemplate.save(comment);
        //3、修改动态表中的评论总数,更新并返回    update xxx set commentCount = xxx where id=？

        Query query = Query.query(Criteria.where("id").is(movementId));
        Update update = new Update();
        if(comment.getCommentType() == 1) { //点赞
            update.inc("likeCount",1); //对此字段数据 +1
        }else if(comment.getCommentType() == 2){ //评论
            update.inc("commentCount",1); //对此字段数据 +1
        }else { //喜欢
            update.inc("loveCount",1); //对此字段数据 +1
        }
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);
        //先更新，查询返回最新的结果
        Movement andModify = mongoTemplate.findAndModify(query, update,
                options, Movement.class);

        //构造返回
        if(comment.getCommentType() == 1) { //点赞
            return andModify.getLikeCount();
        }else if(comment.getCommentType() == 2){ //评论
            return andModify.getCommentCount();
        }else { //喜欢
            return andModify.getLoveCount();
        }
    }

    @Override
    public Boolean hasComment(String movementId, Long userId, Integer commentType) {
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(movementId))
                .and("commentType").is(commentType)
                .and("userId").is(userId);
        Query query = Query.query(criteria);
        //判断数据是否存在，true：存在，false：不存在
        return mongoTemplate.exists(query,Comment.class);
    }

    /**
     * 删除互动数据 （评论，喜欢，点赞）
     * @param movementId    ：动态id
     * @param commentType   ：操作类型
     * @param userId        ：操作人
     * @return
     */
    public Integer delete(String movementId, Integer commentType, Long userId) {
        //删除Comment表中的互动数据
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(movementId))
                .and("commentType").is(commentType)
                .and("userId").is(userId);
        mongoTemplate.remove(Query.query(criteria),Comment.class);
        //更新并获取最新的动态数据（点赞：点赞总数-1。评论：评论总数-1）
        Query query = Query.query(Criteria.where("id").is(movementId));
        Update update = new Update();
        if(commentType == 1) { //点赞
            update.inc("likeCount",-1); //对此字段数据 +1
        }else if(commentType == 2){ //评论
            update.inc("commentCount",-1); //对此字段数据 +1
        }else { //喜欢
            update.inc("loveCount",-1); //对此字段数据 +1
        }

        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);
        //先更新，查询返回最新的结果
        Movement andModify = mongoTemplate.findAndModify(query, update,
                options, Movement.class);
        //构造返回
        if(commentType == 1) { //点赞
            return andModify.getLikeCount();
        }else if(commentType == 2){ //评论
            return andModify.getCommentCount();
        }else { //喜欢
            return andModify.getLoveCount();
        }
    }
}
